<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>div移动 类似贪吃蛇</title>
		<style type="text/css">
			#app{
				height: 200px;
				width: 200px;
				background-color: #FF0000;
				position: absolute;
			}
		</style>
	</head>
	<body>
		<div id="app">
			
		</div>
		<script type="text/javascript">
		
			window.onload = function(){
				document.onkeydown = function(event){//为document 绑定一个按键按下的事件 
					event = event || window.event ;
					var speed = 100 ;
					var app = document.getElementById('app');
					/* 
					 1表示向右移动
					 2表示向左移动
					 3表示向上移动
					 4表示向下移动
					 */
						// if(event.ctrlKey){
						// 	speed = 300;
						// } else{
						// 	speed = 10 ;
						// } 
						//使x的值等于按键的值event.keyCode;
						var x = 2 ;
						switch(x){
							case 1 :
								app.style.left = app.offsetLeft +speed +'px';//向右 left增大
								break;
							case 2:
								app.style.left = app.offsetLeft-speed+'px';//向左 left减小
								break;
							case 3:
								app.style.top = app.offsetTop-speed+'px';//向上
								break;
							case 4:
								app.style.top = app.offsetTop+speed+'px';//向下
								break;
						}
					
						
					};
					//当按键松开时  停止移动
					/* document.onkeyup = function(){
						dir = 0 ;
					}
			 */
			}
		</script>
	</body>
</html>
